package com.ooqiu.gaming.ui.main.thread.person;


import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ooqiu.gaming.R;
import com.ooqiu.gaming.api.GamingApi;
import com.ooqiu.gaming.api.entities.ActItem;
import com.ooqiu.gaming.api.entities.ActRes;
import com.ooqiu.gaming.api.repository.InformationRepository;
import com.ooqiu.gaming.base.BaseFragment;
import com.ooqiu.gaming.common.entities.GamingUser;
import com.ooqiu.gaming.components.glide.GlideApp;
import com.ooqiu.gaming.components.retrofit.progress.ProgressSubscriber;
import com.ooqiu.gaming.components.storage.UserStorage;
import com.ooqiu.gaming.ui.bind.BindPhoneActivity;
import com.ooqiu.gaming.ui.example.StylePreviewActivity;
import com.ooqiu.gaming.ui.feedback.FeedBackActivity;
import com.ooqiu.gaming.ui.login.LoginActivity;
import com.ooqiu.gaming.ui.person.collect.CollectActivity;
import com.ooqiu.gaming.ui.person.edit_profile.EditProfileActivity;
import com.ooqiu.gaming.ui.person.history.HistoryActivity;
import com.ooqiu.gaming.ui.setting.SettingActivity;
import com.ooqiu.gaming.ui.web.WebActivity;
import com.ooqiu.gaming.utils.LogUtil;
import com.ooqiu.gaming.view.SpringScrollView;
import com.ooqiu.gaming.view.SquareImageView;
import com.ooqiu.gaming.view.option_item.OptionItem;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;
import com.tencent.bugly.beta.Beta;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.net.URLDecoder;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
@Route(path = PersonFragment.PATH)
public class PersonFragment extends BaseFragment implements SpringScrollView.TranslucentChangedListener, OptionItem.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
    public static final String PATH = "/fragment/person";

    UserStorage mUserStorage;
    @BindView(R.id.img_avatar)
    CircleImageView mImgAvatar;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.lay_header)
    FrameLayout mLayHeader;
    @BindView(R.id.lay_car)
    LinearLayout mLayCar;
    @BindView(R.id.imageView)
    ImageView mImageView;
    @BindView(R.id.lay_history)
    LinearLayout mLayHistory;
    @BindView(R.id.lay_wallet)
    LinearLayout mLayWallet;
    //    @BindView(R.id.option_msg)
//    OptionItem mOptionMsg;
//    @BindView(R.id.option_point_square)
//    OptionItem mOptionPointSquare;
//    @BindView(R.id.option_test)
//    OptionItem mOptionTest;
//    @BindView(R.id.option_active)
//    OptionItem mOptionActive;
//    @BindView(R.id.option_mall)
//    OptionItem mOptionMall;
    @BindView(R.id.option_feedback)
    OptionItem mOptionFeedback;
    @BindView(R.id.option_setting)
    OptionItem mOptionSetting;
    @BindView(R.id.scro_person)
    SpringScrollView mScroPerson;
    //    @BindView(R.id.fake_status_bar)
//    View mFakeStatusBar;
//    @BindView(R.id.topbar)
//    Topbar mTopbar;
//    @BindView(R.id.ll_action_bar)
//    LinearLayout mLlActionBar;
    @BindView(R.id.lay_login)
    LinearLayout mLayLogin;
    @BindView(R.id.img_login_phone)
    SquareImageView mImgLoginPhone;
    @BindView(R.id.img_login_qq)
    SquareImageView mImgLoginQq;
    @BindView(R.id.img_login_wechat)
    SquareImageView mImgLoginWechat;
    @BindView(R.id.img_login_sina)
    SquareImageView mImgLoginSina;
    @BindView(R.id.lay_logout)
    GridLayout mLayLogout;


    GamingApi mGamingApi;

    UMShareAPI mUMShareAPI;

    InformationRepository mRepository;
    @BindView(R.id.swiper)
    SwipeRefreshLayout mSwiper;


    @BindView(R.id.act_group)
    QMUIGroupListView mGroupListView;


    View.OnClickListener mItemClicker = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getTag() != null && v.getTag() instanceof ActItem) {
                ActItem actItem = (ActItem) v.getTag();
//                if (actItem.getUrl().contains("#")) {
//                    gotoWeb(URLDecoder.decode(assembleUrl(actItem.getUrl()).toString()));
//                } else {
                    gotoWeb(URLDecoder.decode(assembleUrl(actItem.getUrl()).toString()));
//                }
            }
        }
    };


    public PersonFragment() {

    }


    @Override
    public void initInjector(View view) {
        ButterKnife.bind(this, view);
        mUserStorage = getApplicationComponent().getUserStorage();
        mGamingApi = getApplicationComponent().getGamingApi();
        mUMShareAPI = getApplicationComponent().getUMShareAPI();
        mRepository = getApplicationComponent().getRepository();
    }

    @Override
    public int initContentView() {
        return R.layout.fragment_person;
    }

    @Override
    public void initUI(View view) {
        //设置透明度变化监听
        mScroPerson.setTranslucentChangedListener(this);
        //关联需要渐变的视图
//        mScroPerson.setTransView(mLlActionBar, getResources().getDrawable(R.drawable.shape_statuebar), 10, SizeUtils.dip2px(getContext(), 120));
        //关联伸缩的视图
        mScroPerson.setPullZoomView(mLayHeader);
        mLayHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getRouter().build(HistoryActivity.PATH).navigation();
            }
        });


        mLayCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getRouter().build(CollectActivity.PATH).navigation();
            }
        });


        mOptionSetting.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {


                getRouter().build(StylePreviewActivity.PATH).navigation();

                return true;
            }
        });

//        mOptionMsg.setOnItemClickListener(this);
//        mOptionPointSquare.setOnItemClickListener(this);
//
//        mOptionPointSquare.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//                ToastUtil.showWarning("当前为测试模式");
//                gotoWeb("http://www.ooqiuimg.com/wxpay_return1.php?out_trade_no=1111&type=3&total_amount=1");
//                return true;
//            }
//        });

        mSwiper.setOnRefreshListener(this);

//        mOptionTest.setOnItemClickListener(this);
//        mOptionActive.setOnItemClickListener(this);
//        mOptionMall.setOnItemClickListener(this);
        mOptionFeedback.setOnItemClickListener(this);
        mOptionSetting.setOnItemClickListener(this);
        mOptionSetting.showNotice(Beta.getUpgradeInfo() != null);
    }

    @Override
    public void initData() {

    }

    @Override
    public void onTranslucentChanged(int transAlpha) {

//        if (transAlpha <= 40) {
//            mTopbar.setNavTitle("");
//        } else {
//            mTopbar.setNavTitle("个人中心");
//        }
    }


    public void gotoWeb(String url) {
        getRouter().build(WebActivity.PATH)
                .withString("url", url)
                .navigation();
    }


    @Override
    public void onSupportVisible() {
        if (mUserStorage.isLogin()) {
            mLayLogin.setVisibility(View.VISIBLE);
            mLayLogout.setVisibility(View.GONE);
            refreshProfile(mUserStorage.getUser());
            refreshProfileNet();
        } else {
            mLayLogin.setVisibility(View.GONE);
            mLayLogout.setVisibility(View.VISIBLE);
        }

        fetchAct(false);
    }

    @OnClick({R.id.img_avatar, R.id.tv_name, R.id.img_login_phone, R.id.img_login_qq, R.id.img_login_wechat, R.id.img_login_sina})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_avatar:
            case R.id.tv_name:
                getRouter().build(EditProfileActivity.PATH).navigation();
                break;
            case R.id.img_login_phone:
                getRouter().build(LoginActivity.PATH).navigation();
                break;
            case R.id.img_login_qq:
                authorization(SHARE_MEDIA.QQ);
                break;
            case R.id.img_login_wechat:

                authorization(SHARE_MEDIA.WEIXIN);

                break;
            case R.id.img_login_sina:
                authorization(SHARE_MEDIA.SINA);
                break;
        }
    }

    @Override
    public void onItemClick(OptionItem item) {
        switch (item.getId()) {
//            case R.id.option_msg:
//                getRouter().build(MessageActivity.PATH).navigation();
//                break;
//            case R.id.option_point_square:
//
//
////                startActivity(new Intent(mContext, WebViewTestActivity.class));
////                gotoWeb(assembleUrl("http://wxpay.wxutil.com/mch/pay/h5.v2.php").toString());
//                gotoWeb(assembleUrl("http://www.ooqiuimg.com/dist/purchase.html").toString());
//
////                startActivity(new Intent(mContext, AuthActivity.class));
//
////                getRouter().build(StylePreviewActivity.PATH).navigation();
//                break;
//            case R.id.option_test:
//
//
//                gotoWeb(URLDecoder.decode(assembleUrl("http://www.ooqiuimg.com/yyg/").appendPath("#").toString()));
////                gotoWeb(assembleUrl("http://apps.ooqiu.com/bwc/index.html"));
//                break;
//            case R.id.option_active:
////                gotoWeb("http://apps.ooqiu.com/xyc/index.html");
//                gotoWeb(assembleUrl("http://www.ooqiuimg.com/xyc/dist/").appendPath("#").toString());
////                gotoWeb(assembleUrl("http://apps.ooqiu.com/xyc/dist/"));
//                break;
//            case R.id.option_mall:
//                gotoWeb(assembleUrl("http://www.ooqiuimg.com/demo/").appendPath("#").toString());
//                break;
            case R.id.option_feedback:
                getRouter().build(FeedBackActivity.PATH).navigation();
                break;
            case R.id.option_setting:
                getRouter().build(SettingActivity.PATH).navigation();
                break;
        }

    }


    private void refreshProfileNet() {
        mGamingApi.fetchProfile(0)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<GamingUser>(mContext) {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onNext(GamingUser user) {
                        mUserStorage.saveUser(user, false);


                        refreshProfile(mUserStorage.getUser());
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }


    private void refreshProfile(GamingUser user) {
//        mOptionMsg.showNotice(user.getMsg_count() > 0);
        mTvName.setText(user.getName());
        GlideApp.with(mContext).load(user.getFace())
                .error(R.mipmap.ic_default_header)
                .dontAnimate()
//                .placeholder(R.mipmap.ic_default_header)
                .into(mImgAvatar);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(getActivity()).onActivityResult(requestCode, resultCode, data);
    }


    private void authorization(SHARE_MEDIA share_media) {
        UMShareAPI.get(getActivity()).getPlatformInfo(getActivity(), share_media, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                LogUtil.e("onStart " + "授权开始");
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                LogUtil.e("onComplete " + "授权完成");
                LogUtil.json(map);
                JSONObject parseMap = JSON.parseObject(JSON.toJSONString(map));
                if (share_media == SHARE_MEDIA.QQ) {
                    thirdLogin(1, parseMap.getString("openid"), parseMap.getString("name"), parseMap.getString("profile_image_url"));
                } else if (share_media == SHARE_MEDIA.SINA) {
                    thirdLogin(3, parseMap.getString("id"), parseMap.getString("name"), parseMap.getString("avatar_large"));
                } else if (share_media == SHARE_MEDIA.WEIXIN) {
                    thirdLogin(2, parseMap.getString("openid"), parseMap.getString("name"), parseMap.getString("avatar_large"));
                }
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                LogUtil.e("onError " + "授权失败");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                LogUtil.e("onCancel " + "授权取消");
            }
        });
    }


    private void thirdLogin(final int type, String open_id, String nickName, String face) {
        mGamingApi.thirdLogin(type, open_id, nickName, face)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<GamingUser>(mContext) {
                    @Override
                    public void onNext(GamingUser user) {
                        if (TextUtils.isEmpty(user.getMobile())) {
                            getRouter().build(BindPhoneActivity.PATH)
                                    .withInt("login_type", type)
                                    .withString("token", user.getToken())
                                    .navigation();
                        } else {
                            mUserStorage.saveUser(user);
                            onSupportVisible();
                        }
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }

    private String assembleUrl(String url) {

        return url + "?platform=android";

//        if (!TextUtils.isEmpty(url)) {
//            Uri.Builder builder = Uri.parse(url).buildUpon().appendQueryParameter("platform", "android");
//            if (mUserStorage.isLogin()) {
//                builder.appendQueryParameter("token", mUserStorage.getToken());
//            }
//            return builder;
//        }
//        return null;
    }


    /**
     * @param evivt 传入true不使用缓存  false使用缓存规则
     */
    private void fetchAct(boolean evivt) {
        mRepository.fetchActivity(evivt)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<ActRes>(mContext) {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onNext(ActRes acts) {

                        mGroupListView.removeAllViews();

                        if (!acts.getG1().isEmpty()) {
                            QMUIGroupListView.Section section = QMUIGroupListView.newSection(mContext);
                            section.setTitle("");
                            for (ActItem actItem : acts.getG1()) {
                                QMUICommonListItemView itemView = mGroupListView.createItemView(actItem.getTitle());
                                itemView.getTextView().setTextAppearance(mContext, R.style.TopBarMainText_Black);
                                itemView.getDetailTextView().setTextAppearance(mContext, R.style.OptionItemSubText_Gay);
                                itemView.setDetailText(actItem.getDescription());
                                itemView.setTag(actItem);
                                itemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
                                section.addItemView(itemView, mItemClicker);
                            }
                            section.addTo(mGroupListView);
                        }

                        if (!acts.getG2().isEmpty()) {
                            QMUIGroupListView.Section section = QMUIGroupListView.newSection(mContext);
                            section.setTitle("");
                            for (ActItem actItem : acts.getG2()) {
                                QMUICommonListItemView itemView = mGroupListView.createItemView(actItem.getTitle());
                                itemView.getTextView().setTextAppearance(mContext, R.style.TopBarMainText_Black);
                                itemView.getDetailTextView().setTextAppearance(mContext, R.style.OptionItemSubText_Gay);
                                itemView.setDetailText(actItem.getDescription());
                                itemView.setTag(actItem);
                                itemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
                                section.addItemView(itemView, mItemClicker);
                            }
                            section.addTo(mGroupListView);
                        }

                        if (!acts.getG3().isEmpty()) {
                            QMUIGroupListView.Section section = QMUIGroupListView.newSection(mContext);
                            section.setTitle("");
                            for (ActItem actItem : acts.getG3()) {
                                QMUICommonListItemView itemView = mGroupListView.createItemView(actItem.getTitle());
                                itemView.getTextView().setTextAppearance(mContext, R.style.TopBarMainText_Black);
                                itemView.getDetailTextView().setTextAppearance(mContext, R.style.OptionItemSubText_Gay);
                                itemView.setDetailText(actItem.getDescription());
                                itemView.setTag(actItem);
                                itemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
                                section.addItemView(itemView, mItemClicker);
                            }
                            section.addTo(mGroupListView);
                        }


                    }

                    @Override
                    public void onFinish() {
                        mSwiper.setRefreshing(false);
                    }
                });
    }

    @Override
    public void onRefresh() {
        fetchAct(true);
    }
}
